<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests\admin\ArticleRequest;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ArticleController extends Controller
{
    /**  加载文章列表
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = DB::table('article')
                ->join('user','user.id','=','article.uid')
                ->join('artcon','article.cid','=','artcon.id')->select('article.*','artcon.id as aid','artcon.name','user.name as uname')
                ->where(function($query)use($request){
                    if($request->input('keywords')){
                        $query->where('title','like','%'.$request->input('keywords').'%')
                              ->orwhere('uid','like','%'.$request->input('keywords').'%')
                              ->orwhere('cid','like','%'.$request->input('keywords').'%')
                              ->orwhere('des','like','%'.$request->input('keywords').'%');
                    }
                })
                ->paginate($request->input('num',5));
        return view('/admin.article.list',['data'=>$data,'request'=>$request]);
    }

    /** 访问添加文章页面
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //添加文章页面
        $data = DB::table('artcon')->get();
        return view('/admin.article.add',['data'=>self::cate()]);
    }

    /**  执行添加操作
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ArticleRequest $request)
    {    
         $data = self::dataimg($request);
         // $data = $request->except(['_token']);
         // $data['uid'] = session('user')['id']; //section中的用户登录id
         // $data['time']=time();
        
        if(DB::table('article')->insert($data)){
            return redirect('/article')->with('success','添加成功');
        }else{
            return back()->with('error','添加失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**   加载修改页面 -------------------------------------------------------xxxxxxxxxxxxxx-----------------------
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {   
    
        $data = DB::table('article')->where('id',$id)->first();
       
        return view('/admin.article.edit',['data'=>$data,'cate'=>self::cate()]);
    }

    /**   执行修改
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
         $data = self::dataimg($request);
        
        // dd($data);
        if(DB::table('article')->where('id',$id)->update($data)){
            return redirect('/article')->with('success','修改成功');
        }else{
            return back()->with('error','修改失败');
        }
    }

    /**  执行删除操作
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {   
        $data = DB::table('article')->where('id',$id)->first();

        //删除主图
        if(file_exists('.'.$data['pic'])){
            unlink('.'.$data['pic']);
        }

        //删除编辑器中的图片
        preg_match_all('/src=[\'\"]?([^\'\"]*)[\'\"]?/i',$data['con'],$temp);
        foreach($temp[1] as $v){
            if(file_exists('.'.$v)){
                unlink('.'.$v);
            }
        }

        //删除数据
        if(DB::table('article')->where('id','=',$id)->delete()){

            return redirect('/article')->with('success','删除成功');
        }else{
            return back()->with('error','删除失败');
        }
    }

    //生成无限分类下拉框
    public static function cate(){
        $data = DB::table('artcon')
            ->select(DB::raw("*,concat(path,',',id) as paths"))
            ->orderBy('paths')
            ->get();
        foreach($data as $k=>$v){
            $data[$k]['name'] =str_repeat('|---',count(explode(',',$v['path']))-1).$v['name'];
        }
  
        return $data;
    }

    //数据处理, 上传图片
    public static function dataimg($request){
 
         $data = $request->except(['_token','_method']);
         $data['uid'] = session('user')['id']; //section中的用户登录id
         $data['time']=time();
        if($request->hasFile('pic')){
            do{
                //随机图片名
                $picname = md5(time()+rand(0,999));
                //获取文件夹后缀名
                $suffix = $request->file('pic')->getClientOriginalExtension();
                //拼装文件路径
                $path = $picname.'.'.$suffix;
            }while(file_exists('./uploads/'.'.'.$path));
            
            //移动文件夹到指定路径
            $request->file('pic')->move('./uploads/',$path);
            $data['pic']=trim('./uploads/'.$path,'.');// /uploads/44cbfe16d4e342ebb7980c7082a332fc.jpg
        }
        return $data;
        
    }
}
